package com.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.io.Resource;
import com.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created with IDEA by ChouFy on 2020/2/20.
 *
 * @author Zhoufy
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {

        this.configuration = new Configuration();
    }

    /**
     * 该方法就是将配置文件内容解析 封装Configuration
     * 采取dom4j方式
     *
     * @param in
     * @return
     */
    public Configuration paresConfig(InputStream in) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        DruidDataSource dataSource = new DruidDataSource();
//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
//        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcURL"));
//        comboPooledDataSource.setUser(properties.getProperty("username"));
//        comboPooledDataSource.setPassword(properties.getProperty("password"));

        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        dataSource.setUrl(properties.getProperty("jdbcURL"));
        configuration.setDataSource(dataSource);

        List<Element> mapperList = rootElement.selectNodes("//mapper");

        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream mapperInputStream = Resource.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuild = new XMLMapperBuilder(configuration);
            xmlMapperBuild.parse(mapperInputStream);
        }
        return configuration;
    }
}
